package com.example.ktdemo.progressbar;

import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.animation.LinearInterpolator;
import android.widget.ProgressBar;

/**
 * FileName: ProgressAnimBar
 * Author: lzt
 * Date: 2022/9/22 14:44
 * 带动画的进度条
 */
public class ProgressAnimBar extends ProgressBar {
    //需要设置的进度
    private int mSetProgress = 0;
    //属性动画
    private ValueAnimator mValueAnimation;

    public ProgressAnimBar(Context context) {
        super(context);
    }

    public ProgressAnimBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ProgressAnimBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public synchronized void setMax(int max) {
        super.setMax(max);
    }

    @Override
    public synchronized int getProgress() {
        return super.getProgress();
    }

    @Override
    public synchronized void setProgress(int progress) {
        clearAnimation();
        if (this.mValueAnimation != null) {
            this.mValueAnimation.cancel();
        }
        this.removeCallbacks(progressRunnable);
        this.mSetProgress = progress;
        this.postDelayed(progressRunnable, 300);
    }

    private Runnable progressRunnable = new Runnable() {
        @Override
        public void run() {
            setProgressWithAnim(mSetProgress);
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        clearAnimation();
        if (this.mValueAnimation != null) {
            this.mValueAnimation.cancel();
        }
        mValueAnimation = null;
        this.removeCallbacks(progressRunnable);
        super.onDetachedFromWindow();
    }

    /**
     * 设置进度时，动画显示
     *
     * @param progress 需要设置的进度
     */
    protected void setProgressWithAnim(int progress) {
        int currentProgress = getProgress();
        if (progress == currentProgress) {
            super.setProgress(progress);
            return;
        }
        //动画设置进度条
        mValueAnimation = ValueAnimator.ofInt(currentProgress, progress);
        mValueAnimation.setDuration(300);
        mValueAnimation.setInterpolator(new LinearInterpolator());
        mValueAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                try {

                } catch (Exception e) {
                    e.printStackTrace();
                }
                int animValue = (int) animation.getAnimatedValue();
                ProgressAnimBar.super.setProgress(animValue);
            }
        });
        mValueAnimation.start();
    }
}
